package struts.util;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.jdt.internal.compiler.ast.SuperReference;

import struts.annotation.Action;
import struts.annotation.Bean;
import struts.annotation.Forward;
import struts.annotation.Path;

public class BeanUtil {
	
	private Map<String, Class> actionMap = new HashMap<String,Class>();
	
	private Map<String, Class> beanMap = new HashMap<String,Class>();
	
	private Map<String, Map<String,String>> forwardMap = new HashMap<String,Map<String,String>>();

	public Map<String, Class> getActionMap() {
		return actionMap;
	}

	public void setActionMap(Map<String, Class> actionMap) {
		this.actionMap = actionMap;
	}

	public Map<String, Class> getBeanMap() {
		return beanMap;
	}

	public void setBeanMap(Map<String, Class> beanMap) {
		this.beanMap = beanMap;
	}

	public Map<String, Map> parseBean() {
		String classpath = BeanUtil.class.getClassLoader().getResource("").getPath();
		File root = new File(classpath);
		loop(root,"");
		Map<String, Map> map = new HashMap<String,Map>();
		map.put("bean", beanMap);
		map.put("action", actionMap);
		map.put("forward", forwardMap);
		return map;
	}
	
	private void loop(File folder,String pathName) {
		File[] files = folder.listFiles();
		for (File file : files) {
			if(file.isDirectory()) {
				loop(file,pathName+file.getName()+".");
			} else {
				listMethodNames(file,pathName);
			}
		}
	}
	
	private void listMethodNames(File file,String pathName) {
		String fileName = file.getName();
		if(fileName.contains(".class")) {
			String className = fileName.substring(0, fileName.indexOf('.'));
			try {
				System.out.println(pathName+className);
				Class clazz = Class.forName(pathName+className);
				System.out.println(clazz);
				if(clazz.isAnnotationPresent(Action.class)) {
					Action action = (Action) clazz.getAnnotation(Action.class);
					actionMap.put(action.value(), clazz);
				} else if (clazz.isAnnotationPresent(Bean.class)) {
					Bean bean = (Bean) clazz.getAnnotation(Bean.class);
					beanMap.put(bean.value(), clazz);
				} else if (clazz.isAnnotationPresent(Forward.class)) {
					Forward forward = (Forward) clazz.getAnnotation(Forward.class);
					String forwardName = forward.value();
					Field[] fields = clazz.getDeclaredFields();
					Map<String, String> pathMap = new HashMap<String,String>();
					for(Field field : fields) {
						if(field.isAnnotationPresent(Path.class)){
							Path path = field.getAnnotation(Path.class);
							pathMap.put(field.getName(), path.value());
						}
					}
					forwardMap.put(forwardName, pathMap);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
